package goboot

import (
	"net/http"

	"gitee.com/rainsuperman/goboot/def_config"
)

type ServerConfig struct {
	StaticFileDir    *string                                               // 静态文件目录
	GobootWebUrlJson string                                                // 路由json文件路径
	HandleReturn     func(w http.ResponseWriter, retObj any, retErr error) // 返回处理函数，系统提供了默认的返回处理，可自定义修改
}

// RestController 接口
// 所有的自动RestController都需要实现这个接口
type RestController interface {
	GoBootBaseUrl() string // 控制器的基础路径可以为/根路径
}

var serverConfig ServerConfig
var restControllers []RestController
var controllerPackageNameMap map[RestController]string = make(map[RestController]string)
var controllerStructNameMap map[RestController]string = make(map[RestController]string)

// 获取所有的WebDocMethod
func GetWebDocMethodList() []*WebDocMethod {

	return webDocMethodList
}

// 添加RestController
func AddRestController(packageName string, structName string, controller RestController) {
	restControllers = append(restControllers, controller)
	controllerPackageNameMap[controller] = packageName
	controllerStructNameMap[controller] = structName
}

// 监听并服务
func ListenAndServe(addr string, handler http.Handler) error {
	staticFileDir := "./static"

	err := ListenAndServeWithConfig(addr, ServerConfig{
		StaticFileDir:    &staticFileDir,
		GobootWebUrlJson: "gobootWebUrlJsonDoNotEdit.json",
		HandleReturn: func(w http.ResponseWriter, retObj any, retErr error) {

			def_config.HandleReturn(retObj, retErr, w)
		},
	}, handler)

	return err
}

func ListenAndServeWithConfig(addr string, config ServerConfig, handler http.Handler) error {

	serverConfig = config
	webRoute(config.StaticFileDir)
	err := http.ListenAndServe(addr, handler)

	return err
}
